package com.momo.encoderHandler2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.time.LocalDateTime;

/**
 * @author Kagome
 * @title: MyClientHandler
 * @projectName boot2.X-netty
 * @description: TODO
 * @date 2019/6/1 10:09
 */
public class MyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count=0;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] buffer = new byte[msg.readableBytes()];
        msg.readBytes(buffer);
        String msgStr = new String(buffer, Charset.forName("utf-8"));
        System.out.println("客户端接收到服务器端消息："+msgStr);
        System.out.println("客户端接收到服务器端消息次数："+(++count));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i=0;i<10;i++){
            ByteBuf byteBuf = Unpooled.copiedBuffer("sent from client", Charset.forName("utf-8"));
            ctx.writeAndFlush(byteBuf);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.getCause();
        ctx.close();
    }
}
